<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<div id="app">

    <h2>请选择所购买的图书</h2>
    <hr>
    <br>
    <ul>
        <li v-for="(item,index) in arr" :key="index">
            {{item.name}} <button @click="buyBook(index)">购买</button>
        </li>
    </ul>
<!-- cellspacing是表格单元格之间的距离 -->
<table border="1" width="500" cellspacing="0">  
    <tr>
      <th>序号</th>
      <th>书名</th>
      <th>单价</th>
      <th>数量</th>
      <th>合计</th>
    </tr>
    <tr v-for="(item, index) in arr" :key="index">
      <th>{{index}}</th>
      <th>{{item.name}}</th>
      <th>{{item.price}}</th>
      <th>{{item.count}}</th>
      <th>{{item.price * item.count}}</th>
    </tr>
  </table>
<p>总计：{{totalPrice}}</p>
</div>
</body>

<script src="http://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script>

<script>
    const app = new Vue({
        el: "#app",
        data: {
          arr: [
            {
              name: "水浒传",
              price: 10,
              count: 0,
            },
            {
              name: "西游记",
              price: 30,
              count: 0,
            },
            {
              name: "三国演义",
              price: 25,
              count: 0,
            },
            {
              name: "红楼梦",
              price: 15,
              count: 0,
            },
          ],
        },
        methods: {
          buyBook(id) {
            this.arr[id].count++;
          },
        },
        computed: {
          totalPrice() {
            return this.arr.reduce(
              (sum, item) => sum + item.price * item.count,
              0
            );
          },
        },
      });
</script>



</html>